<?php
class LevelAction extends CommonAction {

    public function index() {
        $level = D('Level');
        parent::search(array(
            'name'=>'等级名称'
        ));

        if(!isset($_GET['act'])) {
            parent::page($level->count());
            $allLevel = $level->field(array('name', 'info', 'id'))->limit($this->limit)->select();
        } else if(isset($_GET['act']) && $_GET['act'] == 'search') {
            parent::page($level->where($this->map)->count());
            $allLevel = $level->field(array('name', 'info', 'id'))->where($this->map)->limit($this->limit)->select();
        }


        $this->assign('alllevel', $allLevel);
        $this->assign('empty', '<tr><td colspan="4">没有任何数据</td></tr>');
        $this->display();
    }

    public function add() {
        if(isset($_POST['send'])) {
            $level = D('Level');
            if($level->create()) {
                $level->add() ? $this->success('添加等级成功!', __URL__) : $this->error('系统错误，添加等级失败!', 0);
            } else {
                $this->error($level->getError());
            }
        }
        $this->display();
    }

    public function update() {
        $id = $this->_get('id');
        if(isset($id)) {
            $level = D('Level');
            if(isset($_POST['send'])) {
                if($level->create()) {
                    $level->save() ? $this->success('修改等级成功!', __URL__) : $this->error('系统出错，修改等级失败!', 0);
                } else {
                    $this->error($level->getError());
                }
            }
            $oneLevel = $level->field(array('id','name','info'))->where('id='.$id)->find();
            $this->assign('level',$oneLevel);
            $this->display();
        }
    }

    public function delete() {
        $id = $this->_get('id');
        if(isset($id)) {
            $level = D('Level');
            $admin = D('Admin');
            if(!$level->field('id')->where('id='.$id)->find()) $this->error('不存在此数据!', 0);
            if($admin->field('id')->where('level='.$id)->find()) $this->error('此等级尚有使用的管理员，请先把这些管理员删除!', 0);
            $level->where('id='.$id)->delete() ? $this->success('删除等级成功!', __URL__) : $this->error('系统错误，删除等级失败!', 0);
        }
    }

    public function mulDelete() {
        $level = D('Level');
        $admin = D('Admin');
        $idArr = $this->_post('select');
        if(!$idArr) $this->error('请先勾选一个选项!', 0);
        $ids = implode(',', $idArr);
        $adminMap['level'] = array('in', $ids);
        if($admin->field('id')->where($adminMap)->find()) $this->error('该批等级尚有使用的管理员，请先把这些管理员删除!', 0);
        $levelMap['id'] = array('in', $ids);
        $level->where($levelMap)->delete() ? $this->success('批量删除等级成功!', __URL__) : $this->error('系统出错，批量删除等级失败!');
    }

    public function uniqueName() {
        $level = D('Level');
        $name = $this->_post('name');
        echo $level->where("name='$name'")->getField('id') ? 1 : 0;
    }

}

?>